package com.zjl.SpringBoot.第09章_中间件.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.Charset;

@Controller
@ResponseBody//这个地址转换  不能使用 此注解，此注解的意思是返回值是数据，就不能被 templates 所识别了
@SpringBootApplication(
        exclude = {DataSourceAutoConfiguration.class}
)
@RequestMapping(value = "/redis")//请求地址必须唯一   否者报错，
public class NoSQL {
    public static void main(String[] args) {
        System.setProperty("spring.profiles.active","redis");
        SpringApplication.run(NoSQL.class, args);
        System.err.println("***********启动完毕**当前编码:" + Charset.defaultCharset().name() + "****************");

    }

    @Autowired //注意要序列化
    RedisTemplate<String, Object> redisTemplate;

    @RequestMapping(value = "/set")
    public void set(String key,String value){
        //http://127.0.0.1:8080/redis/set?key=k1&value=v1
        redisTemplate.opsForValue().set(key,value);
    }
    @RequestMapping(value = "/get")
    public Object get(String key){

        //http://127.0.0.1:8080/redis/get?key=k1
        return redisTemplate.opsForValue().get(key);
    }
    @RequestMapping(value = "/delete")
    public Boolean  delete(String key){
        //http://127.0.0.1:8080/redis/delete?key=k1
        return redisTemplate.delete(key);
    }
}
@Configuration
class MyConfiguration{
    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);

        //设置默认的  序列化工具 为  Json    因为java的序列化器，其他软件  如c++ 不认，使用json  可以公共使用
        redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}